package com.zzty.zzlp.controller;

import com.zzty.zzlp.commom.PropertyUtil;
import com.zzty.zzlp.entity.MobieMsg;
import com.zzty.zzlp.entity.User;
import com.zzty.zzlp.entity.User_info;
import com.zzty.zzlp.service.UserService;
import com.zzty.zzlp.util.CreatePicByWord;
import com.zzty.zzlp.util.MsgCheck;
import com.zzty.zzlp.util.MsgSend;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/Register")
public class RegisterController {

    @Autowired
    private JavaMailSenderImpl sender;

    @Autowired
    UserService userService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/AddUserWithMail")
    @ResponseBody
    public Boolean addUser(@RequestBody User user){
        String code= UUID.randomUUID().toString().replace("-", "");
        user.setState(0);
        user.setCode(code);
        userService.addUserByMail(user);
        logger.debug("------StartMailSend-----");
        Boolean successMail = sendMail(user.getEmail(),code);
        logger.debug("------EndMailSend------");
        return successMail;
    }

    public Boolean sendMail(String receiver,String code){
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setTo(receiver);
            mimeMessageHelper.setFrom(PropertyUtil.prop.getProperty("spring.mail.username"));
            mimeMessageHelper.setSubject("自在天原");
            String content = "<html><body>" +"<h3>你好!<br>" +
                    "感谢你注册自在天原，<br>" +
                    "请点击以下链接激活帐号：</h3><br>"+
                    "<h3><a href='http://www.icymi.cn/zzlp/Register/Active?code="+code+"'>http://www.icymi.cn/zzlp/Register/Active</a></h3>" +
                    "</body></html>";
            mimeMessageHelper.setText(content,true);
            sender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @RequestMapping("/Active")
    public void active(@Param("code") String code,HttpServletResponse response){
        User user = userService.findUserByCode(code);
        if(user != null){
            if(userService.getUserByName(user.getName()) != null){
                try {
                    response.sendRedirect("/zzlp/html/abate.html");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                userService.setState(user.getId());
                User tmpUser = userService.findUserByCode(code);
                if(tmpUser.getState() == 1){
                    userService.delCode(tmpUser.getId());
                }
                String img = CreatePicByWord.createImage(user.getName());
                user.setImg(img);
                User_info user_info = new User_info();
                user_info.setuser_id(user.getId());
                user_info.setPhoto(img);
                user_info.setPhone("");
                user_info.setMail(user.getEmail());
                userService.addUserInfo(user_info);
                try {
                    response.sendRedirect("/zzlp/html/login.html");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else{
            try {
                response.sendRedirect("/zzlp/html/abate.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/judgeEmail")
    @ResponseBody
    public Boolean judgeEmail(@RequestBody User user){
        return userService.searchRepeatedEmail(user.getEmail());
    }

    @RequestMapping("/judgeName")
    @ResponseBody
    public Boolean judgeName(@RequestBody User user){
        return userService.searchRepeatedName(user.getName());
    }

    @RequestMapping("/judgeTel")
    @ResponseBody
    public Boolean judgeTel(@RequestBody User user){
        return userService.searchRepeatedTel(user.getTel());
    }

    @RequestMapping("/AddUserWithTel")
    @ResponseBody
    public Boolean addUserWithTel(@RequestBody User user){
        user.setState(1);
        Boolean flag = userService.addUserByTel(user);
        String img = CreatePicByWord.createImage(user.getName());
        User_info user_info = new User_info();
        user_info.setuser_id(userService.getUserByName(user.getName()).getId());
        user_info.setPhoto(img);
        user_info.setPhone(user.getTel());
        user_info.setMail("");
        userService.addUserInfo(user_info);
        return flag;
    }

    @RequestMapping("/sendMsg")
    @ResponseBody
    public Boolean sendMsg(@RequestBody User user){
        try {
            if(MsgSend.sendMsg(user.getTel()).equals("success")){
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    @RequestMapping("/checkMsg")
    @ResponseBody
    public Boolean checkMsg(@RequestBody MobieMsg mobieMsg){
        try {
            if(MsgCheck.checkMsg(mobieMsg.getTel(),mobieMsg.getIdentifyingCode()).equals("success")){
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    @RequestMapping("/judgeLogin")
    @ResponseBody
    public Boolean judgeLogin(@RequestBody User user, HttpServletRequest request){
        Boolean flag = false;
        User tmpUser = null;
        if(user.getEmail() != null && user.getEmail() != ""){
            tmpUser = userService.searchUserByAccNum(user.getEmail(),user.getPassword());
            flag = userService.isRightUser(user.getEmail(),user.getPassword());
        }else  if(user.getTel() != null && user.getTel() != ""){
            tmpUser = userService.searchUserByAccNum(user.getTel(),user.getPassword());
            flag = userService.isRightUser(user.getTel(),user.getPassword());
        }else{
            flag =  false;
        }
        if(flag){
            HttpSession session = request.getSession();
            session.setAttribute("User",tmpUser);
        }
        return flag;

    }


}
